package com.motong.gongdan.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.motong.gongdan.entity.CustomNumber;
import com.motong.gongdan.mapper.CustomNumberMapper;
import com.motong.gongdan.util.TimeUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author:fff
 * @time:2022/5/12
 */
@Service
public class CustomNumberService extends ServiceImpl<CustomNumberMapper, CustomNumber> {
    @Resource
    CustomNumberService customNumberService;

    public String generator(Integer type) {
        CustomNumber cn = customNumberService.getOne(new QueryWrapper<CustomNumber>().eq("type", type));
        if (cn != null) {
            String code = cn.getPrefix();
            if (cn.getTime() == 1) {
                code = code + TimeUtil.getDateYear(new Date());
            } else if (cn.getTime() == 2) {
                code = code + TimeUtil.getDateString(new Date(), "yyyyMM");
            } else if (cn.getTime() == 3) {
                code = code + TimeUtil.getDateString(new Date(), "yyyyMMdd");
            }
            String format = String.format("%0" + cn.getNumber() + "d", cn.getNowNum() + 1);
            if (format.length() > cn.getNumber()) {
                return "fail";
            }
            code = code + format;
            cn.setNowNum(cn.getNowNum() + 1);
            customNumberService.updateById(cn);
            return code;
        }
        return null;
    }
}
